package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.exception.SaveException;
import com.mrd.gtimp.base.entity.Company;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.business.entity.Contacter;
import com.mrd.spring.repository.BaseRepository;
import com.mrd.util.LoginUtil;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

import javax.annotation.Resource;

/**
 * <p>
 * application name: gtimp
 * <p>
 * copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */
@Service
public class ContacterBiz extends BaseBiz<Contacter> {

	@Resource
	// 该处指定注入BaseRepository的dao对象
	@Qualifier("contacterDao")
	public void setBaseRepository(BaseRepository<Contacter, String> baseRepository) {
		super.baseRepository = baseRepository;
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * com.mrd.gtimp.business.biz.ContacterBiz#saveConcater(com.mrd.gtimp.business.pojo.Contacter,
	 * com.mrd.gtimp.base.pojo.Company, java.lang.String)
	 */

	public void saveConcater(Contacter contacter,Company customer,String creator)
	        throws SaveException {
		if(contacter != null) {
			if(null == contacter.getId() || "".equals(contacter.getId())) {
				contacter.setId(null);
				contacter.setOwner(customer);
				contacter.setCREATOR(creator);
				contacter.setCTIME(new Date());
			}
			baseRepository.saveOrupdate(contacter);
		}
	}

	/**
	 * 保存联系人
	 */
	@Transactional
	public Contacter saveContacter() {
		try {
			User currentUser = LoginUtil.getLoginUser();
			Contacter shipper = baseRepository.findOne(currentUser.getId());
			if(shipper == null) {
				Company company = currentUser.getCompany();
				shipper = new Contacter();
				shipper.setId(currentUser.getId());
				shipper.setCompany(company.getName());
				shipper.setName(currentUser.getName());
				shipper.setPhone(company.getPhone());
				shipper.setMobilePhone(currentUser.getMobile());
				shipper.setOwner(company);
				shipper.setAddress(company.getAddress());
				shipper.setZip("");
				shipper.setFax(company.getFax());
				shipper.setEmail(currentUser.getEmail());
				shipper.setCREATOR(currentUser.getAccount());
				baseRepository.save(shipper);
			}
			return shipper;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
